package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.IdCardValidator;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by jiangzx on 2017/3/31.
 * 实名认证
 */
public class RealNameAuthenticationActivity extends BaseActivity {
    public static final String GO_RESULT_ACTIVITY_B="goResult";
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.bt_certification_now)
    Button btCertificationNow;

    @BindView(R.id.et_real_name)
    EditText etRealName;//姓名

    @BindView(R.id.et_id_number)
    EditText etIdNumber;//身份证号码

    boolean goResultActivity;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_identify_verify_page;

        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etRealName.addTextChangedListener(watcher);
        etIdNumber.addTextChangedListener(watcher);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        goResultActivity=getIntent().getBooleanExtra(GO_RESULT_ACTIVITY_B,true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_real_name_authentication;
    }

    private TextWatcher watcher=new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(TextUtils.isEmpty(etRealName.getText())||TextUtils.isEmpty(etIdNumber.getText())){
                btCertificationNow.setEnabled(false);
                btCertificationNow.setAlpha(0.5f);
            }else{
                btCertificationNow.setEnabled(true);
                btCertificationNow.setAlpha(1.0f);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x00f));
        GoogleAnalyticsUtil.setScreenName(Google.REAL_NAME_AUTH);
    }

    @OnClick(R.id.bt_certification_now)
    public void onClick(View v){
        switch (v.getId()){
            case R.id.bt_certification_now:
                //立即认证
                if(checkInput()){
                    SelfUtils.buriedClickData(Self.Action.app_click_identify_verify,
                            Self.Action.app_click_identify_verify_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE,Google.ACTION_REAL_AUTH);
                    verificationIdentityInfo();
                }
                break;
        }
    }

    private boolean checkInput(){
        String realName=etRealName.getText().toString().trim();
        if(!RegularUtil.isName(realName)){
            ToastUtil.showToast("姓名格式错误，请检查");
            return false;
        }else{
            if(realName.contains("*")){
                ToastUtil.showToast("请输入真实姓名");
                return false;
            }
        }
        String idNumber=etIdNumber.getText().toString().trim();
        if(idNumber.contains("*")){
            ToastUtil.showToast("请输入真实身份证号码");
            return false;
        }
        IdCardValidator idCardValidator=new IdCardValidator();
        if(!idCardValidator.isValidatedAllIdcard(idNumber)){
            ToastUtil.showToast("身份证格式错误，请检查");
            return false;
        }
        return true;
    }

    /**提交数据*/
    private void verificationIdentityInfo(){
        showProgressDialog(false);
        final String realName=etRealName.getText().toString().trim();
        final String idNumber=etIdNumber.getText().toString().trim();
        Observable<String> observable=
                Api.realNameIdentify(realName,idNumber,String.valueOf(mApplication.getUser().getID()));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                dismissProgressDialog();
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json=JSON.parseObject(s);
                if(1==json.getIntValue("code")) {
                    //成功
                    UserInfo userInfo=mApplication.getUser();
                    userInfo.setTrueName(realName);
                    userInfo.setIDCardNo(idNumber);
                    if(goResultActivity){
                        initIntent();
                        mIntent.setClass(mContext, RealNamePassActivity.class);
                        mIntent.putExtra(RealNamePassActivity.REAL_NAME, realName);
                        mIntent.putExtra(RealNamePassActivity.IDENTIFY, idNumber);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }else{
                        Event.RealNameInfoNotify realNameInfoNotify=
                                new Event.RealNameInfoNotify();
                        realNameInfoNotify.setName(realName);
                        realNameInfoNotify.setIdNo(idNumber);
                        EventBus.getDefault().post(realNameInfoNotify);
                    }
                    finish();
                }else{
                    //失败
                    ToastUtil.showToastOnScreenCenter(json.getString("msg"));
                }
            }
        });
    }
}
